//
//  UIViewController+Ex.swift
//  TSLiveWallpaper
//
//  Created by 100Years on 2024/12/30.
//

public extension UIViewController {
    func showCustomAlert(
        title: String? = "",
        message: String?,
        rightActionString:String = "Delete".localized,
        deleteHandler: (() -> Void)? = nil,
        cancelHandler: (() -> Void)? = nil
    ) {
        let alert = UIAlertController(title: nil, message: nil, preferredStyle: .alert)
        
        // 自定义标题
        if let title = title {
            let titleAttributes: [NSAttributedString.Key: Any] = [
                .font: UIFont.boldSystemFont(ofSize: 20),
                .foregroundColor: UIColor.white
            ]
            let attributedTitle = NSAttributedString(string: title, attributes: titleAttributes)
            alert.setValue(attributedTitle, forKey: "attributedTitle")
        }
        
        // 自定义消息
        if let message = message {
            let messageAttributes: [NSAttributedString.Key: Any] = [
                .font: UIFont.boldSystemFont(ofSize: 17),
                .foregroundColor: UIColor.white
            ]
            let attributedMessage = NSAttributedString(string: message, attributes: messageAttributes)
            alert.setValue(attributedMessage, forKey: "attributedMessage")
        }
        
        // 添加按钮
        let cancelAction = UIAlertAction(title: "Retain".localized, style: .cancel) { _ in
            cancelHandler?()
        }
        alert.addAction(cancelAction)
        
        let deleteAction = UIAlertAction(title: rightActionString, style: .destructive) { _ in
            deleteHandler?()
        }
        alert.addAction(deleteAction)
        
        // 设置黑暗模式
        alert.overrideUserInterfaceStyle = .dark
        
        // 显示弹窗
        present(alert, animated: true, completion: nil)
    }
    
    
    
    
    
    func showDeleteAlert(
        title: String? = "",
        message: String?,
        deleteHandler: (() -> Void)? = nil,
        cancelHandler: (() -> Void)? = nil
    ) {
        let alert = UIAlertController(title: nil, message: nil, preferredStyle: .alert)
        
        // 自定义标题
        if let title = title {
            let titleAttributes: [NSAttributedString.Key: Any] = [
                .font: UIFont.boldSystemFont(ofSize: 20),
                .foregroundColor: UIColor.white
            ]
            let attributedTitle = NSAttributedString(string: title, attributes: titleAttributes)
            alert.setValue(attributedTitle, forKey: "attributedTitle")
        }
        
        // 自定义消息
        if let message = message {
            let messageAttributes: [NSAttributedString.Key: Any] = [
                .font: UIFont.boldSystemFont(ofSize: 17),
                .foregroundColor: UIColor.white
            ]
            let attributedMessage = NSAttributedString(string: message, attributes: messageAttributes)
            alert.setValue(attributedMessage, forKey: "attributedMessage")
        }
        
        // 添加按钮
        let cancelAction = UIAlertAction(title: "Cancel".localized, style: .cancel) { _ in
            cancelHandler?()
        }
        alert.addAction(cancelAction)
        
        let deleteAction = UIAlertAction(title: "Delete".localized, style: .destructive) { _ in
            deleteHandler?()
        }
        alert.addAction(deleteAction)
        
        // 设置黑暗模式
        alert.overrideUserInterfaceStyle = .dark
        
        // 显示弹窗
        present(alert, animated: true, completion: nil)
    }
    
    
    func showDeleteErrorAlert(
        title: String? = "",
        message: String?,
        deleteHandler: (() -> Void)? = nil,
        cancelHandler: (() -> Void)? = nil
    ) {
        let alert = UIAlertController(title: nil, message: nil, preferredStyle: .alert)
        
        // 自定义标题
        if let title = title {
            let titleAttributes: [NSAttributedString.Key: Any] = [
                .font: UIFont.boldSystemFont(ofSize: 20),
                .foregroundColor: UIColor.white
            ]
            let attributedTitle = NSAttributedString(string: title, attributes: titleAttributes)
            alert.setValue(attributedTitle, forKey: "attributedTitle")
        }
        
        // 自定义消息
        if let message = message {
            let messageAttributes: [NSAttributedString.Key: Any] = [
                .font: UIFont.boldSystemFont(ofSize: 17),
                .foregroundColor: UIColor.white
            ]
            let attributedMessage = NSAttributedString(string: message, attributes: messageAttributes)
            alert.setValue(attributedMessage, forKey: "attributedMessage")
        }
        
        // 添加按钮
        let cancelAction = UIAlertAction(title: "Retain".localized, style: .cancel) { _ in
            cancelHandler?()
        }
        alert.addAction(cancelAction)
        
        let deleteAction = UIAlertAction(title: "Delete".localized, style: .destructive) { _ in
            deleteHandler?()
        }
        alert.addAction(deleteAction)
        
        // 设置黑暗模式
        alert.overrideUserInterfaceStyle = .dark
        
        // 显示弹窗
        present(alert, animated: true, completion: nil)
    }
}




public extension UIViewController {
    /// 简化版 push 带回调
    func push(_ viewController: UIViewController, animated: Bool = true, completion: (() -> Void)? = nil) {
        guard let nav = navigationController else {
            completion?()
            return
        }
        viewController.hidesBottomBarWhenPushed = true
        nav.pushViewController(viewController, animated: animated)
        
        guard animated, let coordinator = nav.transitionCoordinator else {
            DispatchQueue.main.async { completion?() }
            return
        }
        
        coordinator.animate(alongsideTransition: nil) { _ in
            completion?()
        }
    }
}


public extension UINavigationController {
    public enum PushError: Error {
        case noNavigationController
        case alreadyInStack
        case transitionInProgress
        case unknown
    }
    
    func safePushViewController(_ viewController: UIViewController,
                              animated: Bool,
                              completion: @escaping (Result<Void, PushError>) -> Void) {
        // 检查1：导航控制器是否存在
        guard self.viewControllers.isEmpty == false else {
            completion(.failure(.noNavigationController))
            return
        }
        
        // 检查2：是否已经在栈中
        if self.viewControllers.contains(where: { $0 === viewController }) {
            completion(.failure(.alreadyInStack))
            return
        }
        
        // 检查3：是否正在转场
        if self.isBeingPresented || self.isBeingDismissed {
            completion(.failure(.transitionInProgress))
            return
        }
        
        // 执行push
        self.pushViewController(viewController, animated: animated)
        
        // 判断是否动画
        if animated, let coordinator = transitionCoordinator {
            coordinator.animate(alongsideTransition: nil) { _ in
                completion(.success(()))
            }
        } else {
            completion(.success(()))
        }
    }
}

public extension UIViewController {
    /// 判断是否是被 push 进来的
    var isPushed: Bool {
        return navigationController != nil && presentingViewController == nil
    }
    
    /// 判断是否是被 present 进来的
    var isPresented: Bool {
        return presentingViewController != nil
    }
    
    /// 判断是否是 overFullScreen 样式
    var isOverFullScreen: Bool {
        return modalPresentationStyle == .overFullScreen || modalPresentationStyle == .overCurrentContext
    }
    
    /// 获取完整的呈现信息
    var presentationInfo: String {
        if isPushed {
            return "被 push 进入"
        } else if isPresented {
            let style = modalPresentationStyle.description
            return "被 present 进入 - 样式: \(style)"
        } else {
            return "根视图控制器"
        }
    }
}

// 扩展描述
extension UIModalPresentationStyle {
    var description: String {
        switch self {
        case .fullScreen: return "fullScreen"
        case .pageSheet: return "pageSheet"
        case .formSheet: return "formSheet"
        case .currentContext: return "currentContext"
        case .custom: return "custom"
        case .overFullScreen: return "overFullScreen"
        case .overCurrentContext: return "overCurrentContext"
        case .popover: return "popover"
        case .none: return "none"
        case .automatic: return "automatic"
        @unknown default: return "unknown"
        }
    }
}
